package com.tinygray.threadpool;

/**
 * @Author: tinygray
 * @Description: 公众号:Madison龙少，关注我你会越来越优秀。
 * @className: MyThreadPoolDemo
 * @create: 2021-05-09 19:54
 */

import java.util.concurrent.*;

/**
 * 第四种使用获得线程方法 线程池
 */
public class MyThreadPoolDemo {
    public static void main(String[] args) {
        /**
         *  自定义线程池
         *  拒绝策略：
         *      AbortPolicy(): 直接报错
         *      CallerRunsPolicy(): 多出的线程任务 返给上一级 线程 比如这里的mian线程
         *      DiscardOldestPolicy()：把等待时间最长的直接抛弃
         *      DiscardPolicy()：直接把超出的任务抛弃
         */
        System.out.println(Runtime.getRuntime().availableProcessors());
        ExecutorService executorService3 = new ThreadPoolExecutor(
                2,
                5,
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        //一池 固定线程数
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        ExecutorService executorService1 = Executors.newSingleThreadExecutor();
        ExecutorService executorService2 = Executors.newCachedThreadPool();
        //模拟10个用户来办理业务  每一个用户就是来自于外面的线程
        try {
            for (int i = 0; i < 9; i++) {
                executorService3.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t办理业务");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            executorService.shutdown();
//            executorService1.shutdown();
            executorService3.shutdown();
        }
    }
}
